package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/metadata"
	"gorm/grpc/common"
	"log"
)

func main() {

	var outFilter grpc.UnaryClientInterceptor = OutFilter
	//无加密模式
	//conn, err := grpc.Dial(":8899", grpc.WithTransportCredentials(insecure.NewCredentials()))
	//注意这里的拦截器用法，和服务端是不一样的
	conn, err := grpc.Dial(":8899",
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithUnaryInterceptor(outFilter),
	)
	if err != nil {
		panic(err)
	}

	conn.Connect()
	defer func(conn *grpc.ClientConn) {
		err := conn.Close()
		if err != nil {
			log.Fatal("关闭链接异常", err)
		}
	}(conn)

	userClient := common.NewUserClient(conn)
	reply, err := userClient.GetById(context.Background(), &common.UserRequest{Id: 100})
	if err != nil {
		log.Fatal("req err.", err)
	}

	fmt.Printf("[client] got reply: %v\n", reply)

}

func OutFilter(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	// 前置处理逻辑
	log.Println("Method : " + method)
	ctx = metadata.AppendToOutgoingContext(ctx, "username", "admin")
	ctx = metadata.AppendToOutgoingContext(ctx, "password", "admin")

	// 调用invoker 执行远程方法
	err := invoker(ctx, method, req, reply, cc, opts...)

	// 后置处理逻辑
	log.Println(reply)
	return err

	//原文链接：https://blog.csdn.net/weixin_49656607/article/details/128399923
}
